package com.warski.wonderfires.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.constraintlayout.widget.ConstraintLayout;
import com.warski.wonderfires.R;

/**
 * Created by xuhaiping on 2020/8/29.
 * 自定义标题栏
 */
public class TitleBarView extends ConstraintLayout {
    private ImageView rightBtn;
    private ImageView leftBtn;
    private TextView titleText;

    public TitleBarView(Context context, AttributeSet attrs) {
        super(context, attrs);

        initView(context, attrs);
    }

    /**
     * 初始化
     * @param context
     * @param attributeSet
     */
    private void initView(final Context context, AttributeSet attributeSet) {
        View inflate = LayoutInflater.from(context).inflate(R.layout.title_bar, this);
        rightBtn = inflate.findViewById(R.id.titlerightbtn);
        leftBtn = inflate.findViewById(R.id.titleleftbtn);
        titleText = inflate.findViewById(R.id.titletext);

        TypedArray typedArray = context.obtainStyledAttributes(attributeSet, R.styleable.CustomTitleBar);
        String title = typedArray.getString(R.styleable.CustomTitleBar_title);
        int leftIcon = typedArray.getResourceId(R.styleable.CustomTitleBar_left_icon, -1);
        int rightIcon = typedArray.getResourceId(R.styleable.CustomTitleBar_right_icon, -1);

        titleText.setText(title);
        if (rightIcon == -1) {
            rightBtn.setVisibility(View.GONE);
        } else {
            rightBtn.setVisibility(View.VISIBLE);
            rightBtn.setImageResource(rightIcon);
        }
        if (leftIcon == -1) {
            leftBtn.setVisibility(View.GONE);
        } else {
            leftBtn.setVisibility(View.VISIBLE);
            leftBtn.setImageResource(leftIcon);
        }
    }

    /**
     * 设置标题
     * @param text
     */
    public void setTitle(String text){
        titleText.setText(text);
    }

    /**
     * 设置左边按钮点击事件
     * @param listener
     */
    public void setLeftIconOnClickListener(OnClickListener listener) {
        leftBtn.setOnClickListener(listener);
    }

    /**
     * 设置右边按钮点击事件
     * @param listener
     */
    public void setRightIconOnClickListener(OnClickListener listener) {
        rightBtn.setOnClickListener(listener);
    }

    /**
     * 设置左边图标
     * @param resID
     */
    public void setLeftIcon(int resID){
        resId = resID;
        leftBtn.setImageResource(resID);
    }
    private int resId;
    public int getLeftIcon(){
        return resId;
    }

    /**
     * 设置右边图标
     * @param resID
     */
    public void setRightIcon(int resID){
        rightBtn.setImageResource(resID);
    }
}
